import Vue from 'vue';
const WebSql=function(){
	// #ifdef APP-PLUS
    if(window.openDatabase){
        //openDatabase('数据库名称','版本','数据库描述','数据库大小')
        var db = openDatabase('TC','1.0','万',200*1024*1024);
        Vue.prototype.$db=db; 
        if(!db){
            console.log("数据库创建失败！");
        }else{
			db.transaction(function(tx){
				tx.executeSql('CREATE TABLE IF NOT EXISTS Wlh (keyStr, value)');
			});
			Vue.prototype.insertData=function(keyStr,valueStr){
				db.transaction(function(tx){
					tx.executeSql('select value from Wlh where keyStr='+"\""+keyStr+"\"",[],(tx,result)=>{
						let res=result['rows'][0];
						if(typeof res === "undefined"){
							tx.executeSql('INSERT INTO Wlh (keyStr, value) VALUES(?, ?)', [keyStr,valueStr]);//插入数据
						}else{
							tx.executeSql('update Wlh set value = ? where keyStr = ?', [valueStr,keyStr]);//插入数据
						}
					},(tx,error)=>{
						console.log("error:",error);
					});
				});
			}
			Vue.prototype.selectData=function(keyStr,successCall){
				db.transaction(function(tx){
					console.log();
					tx.executeSql('select value from Wlh where keyStr='+"\""+keyStr+"\"",[],(tx,result)=>{
						//res要么有值，要么为undefined
						let res=result['rows'][0];
						successCall(res.value);
					},(tx,error)=>{
						console.log("error:",error);
					});
				});
			}
			console.log("创建数据库成功！");
        }
    }else{
        console.log('不支持本地存储！');
    }
	// #endif
	// #ifdef MP
	Vue.prototype.insertData=function(keyStr,valueStr){
		uni.setStorageSync(keyStr, valueStr);
	}
	Vue.prototype.selectData=function(keyStr,successCall){
		let value = uni.getStorageSync(keyStr);
		successCall(value);
	}
	// #endif
};

export default WebSql;

//example
//通过this.insertData(key,value)使用
//通过this.selectData(key,function(res){
	//todo
//})
//
